package titt.head;

import titt.TITT;
import titt.head.util.AbstractHead;
import titt.service.content.Mimes;

public class FileHead extends AbstractHead {

	private String filename, mime;

	public FileHead(String filename, String mime, HTTPHead h) {
		this(HeadFactory.createHead(h, new Header("Content-Disposition", "attachment; filename=\""+filename+"\""), new Header("Content-Type", mime)));
	}
	
	public FileHead(HTTPHead h) {
		super.h = h;

		String[] split = h.getHeader("Content-Disposition").getValue().split("filename=");
		this.filename = split[1];
		if (filename.startsWith("\""))
			filename = filename.substring(1);
		if (filename.endsWith("\""))
			filename = filename.substring(0,filename.length()-1);
		filename = filename.split("\\\\")[filename.split("\\\\").length-1];		
		
		if(split[0].indexOf("name=\"non-utf-name") != -1)
			filename = TITT.decodeURL(filename);
		
		if(h.getHeader("Content-Type") == null) {
			mime = Mimes.OCTET_STREAM;
			return;
		}
			
			
		mime = h.getHeader("Content-Type").getValue();
		
		if(mime.equals(Mimes.OCTET_STREAM))
			mime = Mimes.getContentType(filename);
	}
	
	public String getFilename() {
		return filename;
	}
	
	public String getFileType() {
		return mime;
	}
	
}
